import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Like } from 'typeorm';
import { dishes, dishCategories } from './dishes.entity'; // 修改实体类命名

interface disheInfo {
  merchant_id?: number,
  name?: string;
  sales?: number;
  rating?: number;
  status?: number;
  category_id?: number;
  is_featured?: number;
}

@Injectable()
export class DishesService {
  constructor(
    @InjectRepository(dishes) private readonly dishsRepository: Repository<dishes>, // 修改实体类引用
    @InjectRepository(dishCategories) private readonly categoriesRepository: Repository<dishCategories>, // 修改实体类引用

  ) { }

  /**
   * 查询菜品列表通过id数组
   * @param ids - 菜品ID数组
   * @returns 菜品列表
   */
  async findListByIds(info: any): Promise<dishes[]> {
    try {
      return await this.dishsRepository.findBy({ id: In(info) }); // 使用 in 查询条件
    } catch (error) {
      throw new Error('Failed to fetch menus by IDs');
    }
  }

  /**
 * 查询菜品列表
 * @param data - 菜品属性，可为{ name, sales, rating, status, category_id, is_featured }
 * @returns 菜品列表
 */
  async findList(data: disheInfo): Promise<dishes[]> {
    // 定义允许的查询字段白名单
    const allowedFields: (keyof disheInfo)[] = ['merchant_id', 'name', 'sales', 'rating', 'status', 'category_id', 'is_featured'];
    // 初始化查询条件
    const queryConditions: Partial<dishes> = {};
    if (data) {
      // 遍历输入数据，仅保留白名单中的字段
      for (const key in data) {
        if (data.hasOwnProperty(key) && allowedFields.includes(key as keyof disheInfo)) {
          queryConditions[key as keyof disheInfo] = data[key];
        }
      }
    } else {
      // 如果 data 为空或未定义，可以选择抛出错误或返回空结果
      console.warn('查询条件为空，将返回所有菜品');
    }
    try {
      // 执行查询
      return await this.dishsRepository.findBy(queryConditions);
    } catch (error) {
      // 抛出带有详细信息的错误
      throw new Error(`数据表查询错误: ${error.message}`);
    }
  }

/**
 * 删除菜品列表
 * @param id - 要删除的菜品ID
 * @returns 操作结果
 */
async deleteDish(id: number): Promise<object> {
  try {
    // 执行删除操作
    const result = await this.dishsRepository.delete(id);
    // 返回成功结果，包含删除操作的结果 
    return { success: true, ...result };
  } catch (error) { 
    // 记录详细的错误信息
    console.error('Error deleting dish:', error);
    // 抛出异常，表示删除菜品失败，并包含详细的错误信息
    throw new Error(`Failed to delete dish with ID ${id}: ${error.message}`);
  }
}

  /**
   * 新增菜品列表
   * @param info - 菜品信息
   * @returns 操作结果
   */
  async addDishs(info: dishes): Promise<object> {
    try {
      const newMenu = this.dishsRepository.create(info);
      return newMenu;
    } catch (error) {
      throw new Error('Failed to add menu');
    }
  }

  /**
   * 修改菜品列表
   * @param info - 菜品信息
   * @returns 操作结果
   */
  async editDishs(info: dishes): Promise<object> {
    try {
      const result = await this.dishsRepository.update(info.id, info);
      return result;
    } catch (error) {
      throw new Error('Failed to edit menu');
    }
  }

  /**
   * 菜品列表详情
   * @param id - 菜品ID
   * @returns 菜品详情
   */
  async oneMenu(id: number): Promise<dishes | null> {
    try {
      return await this.dishsRepository.findOneBy({ id });
    } catch (error) {
      throw new Error('Failed to fetch menu details');
    }
  }
  /**
* 查询菜品列表 分页
* @param info - 菜品列属性
* @returns 菜品列表+总数
*/
  async dishesBypage(info: any): Promise<any> {
    // 校验输入参数
    if (!Array.isArray(info.merchant_id) || info.merchant_id.some((id: number) => typeof id !== 'number')) {
      throw new Error('Invalid merchant_id: must be an array of numbers');
    }

    if (typeof info.pageSize !== 'number' || info.page < 1 || info.pageSize < 1) {
      throw new Error('Invalid pagination parameters: page and pageSize must be positive numbers');
    }

    let data = JSON.parse(JSON.stringify(info));
    delete data.merchant_id;
    delete data.page;
    delete data.pageSize;

    // 构建查询条件
    let whereConditions: any = {
      merchant_id: In(info.merchant_id),
    };

    if (data.name) {
      whereConditions.name = Like(`%${data.name}%`);
      delete data.name;
    }

    whereConditions = { ...whereConditions, ...data };
    // console.log(whereConditions);
    try {
      const [posts, total] = await this.dishsRepository.findAndCount({
        where: whereConditions,
        skip: (info.page - 1) * info.pageSize,
        order: {
          status: 'DESC',
        },
        take: info.pageSize,
      });

      return {
        data: posts,
        total,
        page: info.page,
        pageSize: info.pageSize,
        // ...其他分页信息
      };
    } catch (error) {
      throw new Error('Failed to fetch dishes');
    }
  }
  async oneCategories(id: number): Promise<dishCategories | null> {
    try {
      return await this.categoriesRepository.findOneBy({ id });
    } catch (error) {
      throw new Error('Failed to fetch categories');
    }
  }
  /**
* 查询菜品种类列表或者分页
* @param info - 菜品种类属性
* @returns 菜品种类列表+总数
*/
  async getCategories(info: any): Promise<any> {
    // 校验输入参数
    let data = JSON.parse(JSON.stringify(info))
    delete data.merchant_id
    delete data.page
    delete data.pageSize
    try {
      if (info.page) {
        const [posts, total] = await this.categoriesRepository.findAndCount({
          where: { merchant_id: In([info.merchant_id]), ...data },
          skip: (info.page - 1) * info.pageSize,
          take: info.pageSize,
        });
        return {
          data: posts,
          total,
          page: info.page,
          pageSize: info.pageSize,
          // ...其他分页信息
        };
      }

      return await this.categoriesRepository.findBy({ merchant_id: In(info.merchant_id), ...data }); // 使用 in 查询条件
    } catch (error) {
      throw new Error('Failed to fetch categories');
    }
  }
  /**
 * 查询菜品种类列表或者分页
 * @param info - 菜品种类属性
 * @returns 菜品种类列表+总数
 */
  async categoriesBy(info: any): Promise<any> {
    try {
      // 校验输入参数
      return await this.categoriesRepository.findBy(info); // 使用 in 查询条件
    } catch (error) {
      throw new Error('Failed to fetch categories');
    }
  }
  /**
   * 编辑菜品种类
   * @param info - 菜品种类属性
   * @returns 操作结果
   */
  async editCategories(info: dishCategories): Promise<object> {
    try {
      const result = await this.categoriesRepository.update(info.id, info);
      return result;
    } catch (error) {
      throw new Error('Failed to edit categories');
    }
  }
  /**
   * 新增菜品种类
   * @param info - 菜品种类属性
   * @returns 操作结果
   */
  async addCategories(info: dishCategories): Promise<object> {
    try {
      const newMenu = this.categoriesRepository.create(info);
      return newMenu;
    } catch (error) {
      throw new Error('Failed to add categories');
    }
  }
  /**
   * 删除菜品种类
   * @param id - 要删除的菜品种类ID
   * @returns 操作结果
   */
  async deleteCategories(id: number): Promise<object> {
    try {
      const result = await this.categoriesRepository.delete(id);
      return { success: true, ...result };
    } catch (error) {
      throw new Error('Failed to delete categories');
    }
  }
}
